package dom;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;

import org.w3c.dom.Document;

import org.xml.sax.SAXException;

public class dom {

	Document dom;

	public long validateDOM(String xml,String xsd) {

		// parse the xml file and get the dom object

	
		/*
		 * En milisegundos
		 * long startTime = System.currentTimeMillis();
// ... do something ...
long estimatedTime = System.currentTimeMillis() - startTime;

		 */
		
		long startTime = System.nanoTime();

		parseXmlFile(xml,xsd);
		
		long estimatedTime = System.nanoTime() - startTime;
		System.out.println("Total: "+ estimatedTime +" nanosegundos usando DOM");
		
		// System.out.println(cal.getTime());
		return estimatedTime;

	}

	private void parseXmlFile(String xml,String xsd) {
		// get the factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try {

			SchemaFactory schemaFactory = SchemaFactory
					.newInstance("http://www.w3.org/2001/XMLSchema");

			dbf.setSchema(schemaFactory
					.newSchema(new Source[] { new StreamSource(xsd) }));

			// Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();

			// parse using builder to get DOM representation of the XML file
			dom = db.parse(xml);

		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (SAXException se) {
			se.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

}